// 策略模式
// 思想：定义一系列的算法，把他们一个个的封装起来，并且使他们可以相互替换
// 表单校验
const strategies = {
  isNoEmpty(value, errMsg) {
    if (value === '') return errMsg
  },
  minLength(value, length, errMsg) {
    if (value.length < length) return errMsg
  },
  isMobile(value, errMsg) {
    if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) return errMsg
  }
}

// Validator
function Validator(){
  this.cache = []
  this.add = (value, rules) => {
    for (let i = 0, rule; rule = rules[i++];) {
      let strategyAry = rule.strategy.split(':')
      let errMsg = rule.errMsg
      this.cache.push(() => {
        let strategy = strategyAry.shift()
        strategyAry.unshift(value)
        strategyAry.push(errMsg)
        console.log(strategyAry)
        return strategies[strategy].apply(value, strategyAry)
      })
    }
  }
  this.start = () => {
    for (let i = 0, validationFunc; validationFunc = this.cache[i++];) {
      let errMsg = validationFunc()
      if (errMsg) return errMsg
    }
  }
}

// test
const validator = new Validator()
validator.add('999', [
  { strategy: 'isNoEmpty', errMsg: '用户名不能为空' },
  { strategy: 'minLength:4', errMsg: '最小长度4' }
])
validator.add('123', [
  { strategy: 'minLength:8', errMsg: '最小长度8' }
])
const err = validator.start()
console.log(9999, err)